package org.iweb.init.context;

import java.lang.management.ManagementFactory;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.iweb.init.IRegisterFactory;
import org.iweb.init.classloader.IWebClassLoader;

@WebListener
public class ContextListener implements ServletContextListener,ContextListenerMBean {

	public static IWebClassLoader iWebCl;
	public static boolean isReloaded=true;

	private MBeanServer mbs = null;

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {

		try {
			ObjectName mbame = new ObjectName("FOO:name="+getClass().getName());
			mbs = ManagementFactory.getPlatformMBeanServer();
			mbs.registerMBean(this, mbame);
		} catch (InstanceAlreadyExistsException | MBeanRegistrationException
				| NotCompliantMBeanException | MalformedObjectNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		reload();
	}

	public void reload(){
		try {
			iWebCl=new IWebClassLoader(ContextListener.class.getClassLoader());
			((IRegisterFactory)iWebCl.loadClass("org.iweb.init.RegisterFactory").newInstance()).init(iWebCl);
			isReloaded=true;
		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
